<template>
  <div class="searchTemplatePage">
    <div class="searchBox">
      <div
        v-if="defaultSearchArr && defaultSearchArr.length > 0"
        style="display: inline-block"
      >
        <div
          v-for="(item, index) in defaultSearchArr"
          :key="index"
          class="searchBox-inputBox"
          :style="{
            width:
              item.type === SearchType.DateRange ||
              item.type === SearchType.DateTimeRange
                ? '220px'
                : ''
          }"
        >
          <!-- 默认渲染input -->
          <el-input
            v-if="item.type === SearchType.Input"
            v-model="item.value"
            clearable
            :placeholder="item.placeholder"
          ></el-input>
          <!-- 默认 渲染 下拉列表 -->
          <el-select
            v-else-if="item.type === SearchType.Select"
            v-model="item.value"
            class="searchItem-select"
            clearable
            filterable
            :placeholder="item.placeholder ? item.placeholder : ''"
          >
            <el-option
              v-for="option in item.options"
              :key="option.key"
              :label="option.label"
              :value="option.value"
            >
            </el-option>
          </el-select>
          <el-select
            v-else-if="item.type === SearchType.MultiSelect"
            v-model="item.value"
            class="searchItem-select"
            clearable
            filterable
            multiple
            :placeholder="item.placeholder ? item.placeholder : ''"
          >
            <el-option
              v-for="option in item.options"
              :key="option.key"
              :label="option.label"
              :value="option.value"
            >
            </el-option>
          </el-select>
          <!-- 默认渲染 单个时间格式 -->
          <el-date-picker
            v-else-if="item.type === SearchType.Date"
            v-model="item.value"
            type="date"
            clearable
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptionsDate"
            style="width: 100%"
            align="right"
            placeholder="选择日期"
          >
          </el-date-picker>
          <!-- 默认渲染 时间格式 -->
          <el-date-picker
            v-else-if="
              item.type === SearchType.DateRange ||
                item.type === SearchType.DateTimeRange
            "
            v-model="item.value"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            range-separator="-"
            style="width: 100%"
            start-placeholder="开始"
            end-placeholder="结束"
            align="right"
          >
          </el-date-picker>
        </div>
      </div>
      <el-button
        icon="el-icon-search"
        type="primary"
        class="ml-10"
        @click="onSearch"
      >
        搜索
      </el-button>
      <el-button
        v-popover:popover2
        class="mb-10"
        type="moreSearch"
      >
        更多筛选条件
      </el-button>

      <span
        v-for="(item, index) in selectedSearchParams"
        :key="index"
        class="searchBox-selectTag"
      >
        <span class="label"> {{ item.label }}: </span>
        <!-- 输入框 展示搜索类型 -->
        <span v-if="item.type === SearchType.Input">
          {{ item.tagValue }}
        </span>
        <!-- 输入框 展示搜索类型 -->
        <span
          v-else-if="item.type === SearchType.Select"
        >
          {{
            item.options
              .filter((option) => option.value === item.tagValue)
              .map((v) => v.label)
              .join(", ")
          }}
        </span>
        <span
          v-else-if="item.type === SearchType.MultiSelect"
        >
          {{
            item.options
              .filter((option) => item.tagValue.includes(option.value))
              .map((v) => v.label)
              .join(", ")
          }}
        </span>
        <!-- 区间输入 展示搜索类型 -->
        <span
          v-else-if="
            item.type === SearchType.Interval && item.tagValue.length === 2
          "
        >
          {{ item.tagValue[0] }}
          <span
            style="width: 20px; display: inline-block; text-align: center"
          >-</span>
          {{ item.tagValue[1] }}
        </span>
        <!-- 单个时间选择器 展示搜索类型 -->
        <span v-else-if="item.type === SearchType.Date && item.tagValue">
          {{ item.tagValue }}
        </span>
        <!-- 时间选择器 展示搜索类型 -->
        <span
          v-else-if="
            (item.type === SearchType.DateRange ||
              item.type === SearchType.DateTimeRange) &&
              item.tagValue.length === 2
          "
        >
          {{ item.tagValue[0] }}
          <span
            style="width: 20px; display: inline-block; text-align: center"
          >-</span>
          {{ item.tagValue[1] }}
        </span>
        <i
          class="searchHearder-close close el-icon-close"
          @click="onReset(item.key)"
        ></i>
      </span>
      <el-popover
        ref="popover2"
        placement="bottom-start"
        width="410"
        :offset="-170"
        :visible-arrow="false"
        trigger="click"
      >
        <div class="searchTemplateBox">
          <div class="searchHearder">
            <span class="searchHearder-title"> 筛选条件 </span>
            <i
              class="searchHearder-close el-icon-close"
              @click="$refs.popover2.doClose()"
            ></i>
          </div>
          <div
            v-for="(item, index) in validSearchParams"
            :key="index"
          >
            <!-- input 输入 -->
            <div
              v-if="item.type === SearchType.Input"
              class="searchItem"
            >
              <span class="searchItem-label">{{ item.label }}</span>
              <div class="searchItem-value">
                <el-input
                  v-model="item.value"
                  clearable
                  :placeholder="item.placeholder ? item.placeholder : ''"
                ></el-input>
              </div>
            </div>

            <!-- 下拉选 -->
            <div
              v-else-if="item.type === SearchType.Select"
              class="searchItem"
            >
              <span class="searchItem-label">{{ item.label }}</span>
              <div class="searchItem-value">
                <el-select
                  v-model="item.value"
                  class="searchItem-select"
                  clearable
                  filterable
                  :placeholder="item.placeholder ? item.placeholder : ''"
                >
                  <el-option
                    v-for="option in item.options"
                    :key="option.key"
                    :label="option.label"
                    :value="option.value"
                  >
                  </el-option>
                </el-select>
              </div>
            </div>
            <div
              v-else-if="item.type === SearchType.MultiSelect"
              class="searchItem"
            >
              <span class="searchItem-label">{{ item.label }}</span>
              <div class="searchItem-value">
                <el-select
                  v-model="item.value"
                  class="searchItem-select"
                  clearable
                  filterable
                  multiple
                  :placeholder="item.placeholder ? item.placeholder : ''"
                >
                  <el-option
                    v-for="option in item.options"
                    :key="option.key"
                    :label="option.label"
                    :value="option.value"
                  >
                  </el-option>
                </el-select>
              </div>
            </div>
            <!-- 单个日期选择 -->
            <div
              v-if="item.type === SearchType.Date"
              class="searchItem"
            >
              <span class="searchItem-label">{{ item.label }}</span>
              <div class="searchItem-value">
                <el-date-picker
                  v-model="item.value"
                  type="date"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptionsDate"
                  style="width: 100%"
                  placeholder="选择日期"
                  align="right"
                  clearable
                >
                </el-date-picker>
                <!-- <el-date-picker
                  v-model="item.value"
                  align="right"
                  type="date"
                  placeholder="选择日期"
                  :picker-options="pickerOptions"
                >
                </el-date-picker> -->
              </div>
            </div>
            <!-- 日期选择 -->
            <div
              v-else-if="
                item.type === SearchType.DateRange ||
                  item.type === SearchType.DateTimeRange
              "
              class="searchItem"
            >
              <span class="searchItem-label">{{ item.label }}</span>
              <div class="searchItem-value">
                <el-date-picker
                  v-model="item.value"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions"
                  range-separator="-"
                  style="width: 100%"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  align="right"
                >
                </el-date-picker>
              </div>
            </div>
            <!-- 区间选择 -->
            <div
              v-else-if="item.type === SearchType.Interval"
              class="searchItem"
            >
              <span class="searchItem-label">{{ item.label }}</span>
              <div class="searchItem-value searchItem-Interval">
                <el-input
                  v-model="item.value[0]"
                  clearable
                  placeholder="Min"
                ></el-input>
                -
                <el-input
                  v-model="item.value[1]"
                  clearable
                  placeholder="Max"
                ></el-input>
              </div>
            </div>
          </div>
          <div
            v-if="validSearchParams.length === 0"
            class="no-more"
          >
            无更多筛选条件
          </div>
          <div class="searchFooter">
            <el-button @click="onReset('')">
              重置
            </el-button>
            <el-button
              type="primary"
              @click="onFilter(), $refs.popover2.doClose()"
            >
              筛选
            </el-button>
          </div>
        </div>
      </el-popover>
    </div>
  </div>
</template>

<script lang='ts'>
import { Component, Prop, Vue, Emit } from 'vue-property-decorator'
import { SearchParam, SearchType, ValueType } from '@/models/searchParams'
import { isEmpty, isNotEmpty } from '@/utils/validate'

@Component({})
export default class Page extends Vue {
  @Prop({ required: true }) searchParams!: SearchParam[];

  pickerOptionsDate = {
    shortcuts: [
      {
        text: '最近一周',
        onClick(picker: any) {
          const date = new Date()
          date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
          picker.$emit('pick', date)
        }
      },
      {
        text: '最近一个月',
        onClick(picker: any) {
          const date = new Date()
          date.setTime(date.getTime() - 3600 * 1000 * 24 * 30)
          picker.$emit('pick', date)
        }
      },
      {
        text: '最近三个月',
        onClick(picker: any) {
          const date = new Date()
          date.setTime(date.getTime() - 3600 * 1000 * 24 * 90)
          picker.$emit('pick', date)
        }
      }
    ]
  };

  pickerOptions = {
    shortcuts: [
      {
        text: '最近一周',
        onClick(picker: any) {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          picker.$emit('pick', [start, end])
        }
      },
      {
        text: '最近一个月',
        onClick(picker: any) {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
          picker.$emit('pick', [start, end])
        }
      },
      {
        text: '最近三个月',
        onClick(picker: any) {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
          picker.$emit('pick', [start, end])
        }
      }
    ]
  };

  @Emit()
  onSearch() {
    this.refreshTagValue()
  }

  @Emit()
  onFilter() {
    this.refreshTagValue()
  }

  @Emit()
  onReset(key = '') {
    console.log(key)
    if (isNotEmpty(key)) {
      // 清除指定属性值
      const param = this.searchParams.find(
        (item: SearchParam) => item.key === key
      )
      if (!param) return
      if (param.value instanceof Array) param.value = []
      else param.value = ''
    } else {
      // 清楚全部属性值`
      this.searchParams.forEach((item: SearchParam) => {
        if (item.value instanceof Array) item.value = []
        else item.value = ''
      })
    }
    this.refreshTagValue()
    return key
  }

  refreshTagValue() {
    this.searchParams.forEach((item: SearchParam) => {
      if (item.type === SearchType.Interval && item.value instanceof Array) {
        this.$set(item, 'tagValue', [...item.value])
      } else {
        this.$set(item, 'tagValue', item.value)
      }
    })
  }

  getSearchParamsValues() {
    const map: any = {}
    // return this.searchParams.filter((item:SearchParam) => isNotEmpty(item.value)).map((item:SearchParam) => { return { key: item.key, value: item.value } })
    this.searchParams
      .filter((item: SearchParam) => isNotEmpty(item.value))
      .forEach((item: SearchParam) => {
        // 单个日期
        if (
          // 日期范围类型的存在两个key
          (item.type === SearchType.DateRange ||
            item.type === SearchType.DateTimeRange) &&
          item.keys &&
          item.value &&
          item.value instanceof Array
        ) {
          map[item.keys[0]] =
            item.type === SearchType.DateRange
              ? item.value[0]
              : item.value[0] + ' 00:00:00'
          map[item.keys[1]] =
            item.type === SearchType.DateRange
              ? item.value[1]
              : item.value[1] + ' 23:59:59'
        } else if (
          item.type === SearchType.Interval &&
          item.keys &&
          item.value &&
          item.value instanceof Array
        ) {
          map[item.keys[0]] = item.value[0]
          map[item.keys[1]] = item.value[1]
        } else if (
          item.type === SearchType.MultiSelect &&
          item.value &&
          item.valueType
        ) {
          if (item.valueType === ValueType.CommaSeparated) {
            map[item.key] = item.value instanceof Array && item.value.join(',')
          } else {
            map[item.key] = item.value
          }
        } else {
          map[item.key] = item.value
        }
      })
    return map
  }

  // computed
  get SearchType() {
    return SearchType
  }

  get defaultSearchArr() {
    const defalutArr = this.searchParams.filter(
      (item: SearchParam) => item.default
    )
    return defalutArr
  }

  get selectedSearchParams() {
    return this.searchParams.filter(
      (item: SearchParam) => isNotEmpty(item.tagValue) && !item.default
    )
  }

  get validSearchParams() : SearchParam[] {
    return this.searchParams.filter((item:SearchParam) => isEmpty(item.permission) || (item.permission && this.$hasPermission(item.permission))).filter((item:SearchParam) => isEmpty(item.hide) || (!item.hide))
  }
}
</script>
<style lang="scss" scoped>
.mb-10 {
  margin-bottom: 10px;
}
.no-more {
  text-align: center;
  color: #999;
}
</style>
<style lang='scss'>
.searchTemplateBox {
  padding: 0px 10px;
  .searchHearder {
    display: flex;
    margin-bottom: 20px;
    margin-top: 10px;
    @at-root &-title {
      font-size: 15px;
      flex: 1;
    }
    @at-root &-close {
      font-style: normal;
      cursor: pointer;
    }
  }
  .searchItem {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    .searchItem-label{
      width: 70px;
      font-size: 14px;
      margin-right: 10px;
    }
    @at-root &-select {
      width: 100%;
    }
    .searchItem-value {
      flex: 1;
    }
    .searchItem-Interval {
      > .el-input {
        width: 47%;
        display: inline-block;
      }
    }
  }
  .searchFooter {
    text-align: right;
    margin-top: 20px;
  }
}
.searchTemplatePage {
  .searchBox {
    flex-wrap: wrap;
    @at-root &-inputBox {
      width: 160px;
      margin-right: 10px;
      display: inline-block;
    }
    @at-root &-selectTag {
      border: 1px solid #ddd;
      font-size: 14px;
      border-radius: 2px;
      height: 28px;
      line-height: 28px;
      padding: 0 10px;
      display: inline-block;
      margin-right: 10px;
      vertical-align: top;
      border-radius: 4px;
      .label {
        color: #999;
      }
      .close {
        color: #999;
        cursor: pointer;
      }
    }
  }
  .el-button--moreSearch.is-active,
  .el-button--moreSearch:active {
    background: #20b2aa;
    border-color: #20b2aa;
    color: #fff;
  }

  .el-button--moreSearch:focus,
  .el-button--moreSearch:hover {
    color: #fff;
    border-color: #1ab293;
    background-color: #1ab293;
    opacity: 0.8;
  }

  .el-button--moreSearch {
    color: #fff;
    background-color: #1ab293;
    border-color: #1ab293;
    margin-right: 10px;
  }
}
</style>
